package main

import "fmt"

func main() {
	test_array()
	test_slice()
	test_map()
	test_range()
	test_func()
	test_closures()
}

func test_slice() {
	s := make([]string, 3)
	fmt.Println("空切片:", s)

	//赋值
	s[0] = "a"
	s[1] = "b"
	s[2] = "c"
	fmt.Println("设值:", s)
	fmt.Println("取值:", s[2])
	fmt.Println("长度:", len(s))

	s = append(s, "d")
	s = append(s, "e", "f")
	fmt.Println("添加:", s)

	c := make([]string, len(s))
	copy(c, s)
	fmt.Println("拷贝:", c)

	l := s[2:5]
	fmt.Println("切片1:", l)

	l = s[:5]
	fmt.Println("切片2:", l)

	l = s[2:]
	fmt.Println("切片3:", l)

	twoD := make([][]int, 3)
	for i := 0; i < 3; i++ {
		innerLen := i + 1
		twoD[i] = make([]int, innerLen)
		for j := 0; j < innerLen; j++ {
			twoD[i][j] = i + j
		}
	}
	fmt.Println("2d:", twoD)
}

func test_array() {
	var a [5]int
	fmt.Println("空数组:", a)

	a[4] = 100
	fmt.Println("设置:", a)
	fmt.Println("取值:", a[4])

	fmt.Println("长度:", len(a))

	b := [5]int{1, 2, 3, 4, 5}
	fmt.Println("数组:", b)

	var twoD [2][3]int
	for i := 0; i < 2; i++ {
		for j := 0; j < 3; j++ {
			twoD[i][j] = i + j
		}
	}
	fmt.Println("2d:", twoD)
}

func test_map() {
	m := make(map[string]int)

	m["k1"] = 7
	m["k2"] = 13

	fmt.Println("map:", m)

	v1 := m["k1"]
	fmt.Println("v1:", v1)
	fmt.Println("长度:", len(m))

	delete(m, "k2")
	fmt.Println("map:", m)

	_, prs := m["k2"]
	fmt.Println("prs", prs)

	n := map[string]int{"foo": 1, "bar": 2}
	fmt.Println("map:", n)
}

func test_range() {
	nums := []int{2, 3, 4}
	sum := 0
	for _, num := range nums {
		sum += num
	}
	fmt.Println("合计:", sum)

	for i, num := range nums {
		if num == 3 {
			fmt.Println("索引:", i)
		}
	}

	kvs := map[string]string{"a": "apple", "b": "banana"}
	for k, v := range kvs {
		fmt.Println("%s -> %s\n", k, v)
	}

	for i, c := range "golang" {
		fmt.Println(i, c)
	}
}

func test_func() {
	sum(1, 2)
	sum(1, 2, 3)

	nums := []int{1, 2, 3, 4}
	sum(nums...)
}

func sum(nums ...int) {
	fmt.Print(nums, " ")
	total := 0
	for _, num := range nums {
		total += num
	}
	fmt.Println(total)
}

func intSeq() func() int {
	i := 0
	return func() int {
		i++
		return i
	}
}

func test_closures() {
	nextInt := intSeq()

	fmt.Println(nextInt())
	fmt.Println(nextInt())
	fmt.Println(nextInt())

	newInts := intSeq()
	fmt.Println(newInts())
}
